import React, { useState, useEffect, useRef } from "react";
import { Popconfirm, Button, Image, message, notification } from "antd";
import { PageContainer, FooterToolbar } from "@ant-design/pro-layout";
import { LeftOutlined } from "@ant-design/icons";
import ProTable from "@ant-design/pro-table";

import ProForm, {
  ModalForm,
  ProFormText,
  ProFormList,
  ProFormSelect,
} from "@ant-design/pro-form";
import { history, useLocation } from "umi";
import { ProCard } from "@ant-design/pro-components";
import { addSpec, updateSpec, fetchSpecInfo } from "@/api/package";
import SetBook from "./components/SetBook";
import { BOOK_NUM } from "@/const";

export default () => {
  const [loading, setLoading] = useState(false);
  const {
    schoolbagId,
    cycle,
    specId,
    specification = BOOK_NUM, // 新增的时候从url带过来的
  } = useLocation().query;
  const title = specId ? "编辑规格" : "新增规格";
  const [info, setInfo] = useState({});
  const formRef = useRef();
  const [selectedIds, setSelectedIds] = useState([]);

  // const [phases, setPhases] = useState(
  //   Array.from({ length: cycle }, (_, i) => {
  //     return { phaseNum: i + 1, phaseBooks: [] };
  //   })
  // );

  const getInfo = async () => {
    setLoading(true);
    const res = await fetchSpecInfo({ id: specId });
    setLoading(false);
    if (res.code == 200) {
      setInfo({
        ...res.data,
        schoolbagBookNum: res.data.schoolbagBookNum || BOOK_NUM, // 编辑的时候是根据后端返回的数量限制
      });
      const postData = {
        ...res.data,
      };
      formRef.current.setFieldsValue(postData);
      const selectedArrs = postData.phases
        .map((item) => item.phaseBooks.map((item) => item.booksId))
        .flat();
      console.log("selectedArrs===", selectedArrs);
      setSelectedIds(selectedArrs);
    }
  };

  useEffect(() => {
    if (specId) {
      getInfo();
    } else {
      setInfo({
        schoolbagBookNum: specification, // 新增的时候，取url带过来的
      });
    }
  }, []);

  const handleAddOrUpdate = async (fields) => {
    const postData = {
      ...fields,
      schoolbagId,
    };
    let func = addSpec;
    if (specId) {
      postData.id = specId;
      func = updateSpec;
    }
    const cycles = [];
    postData.phases?.forEach((item) => {
      if (item.phaseBooks.length != info.schoolbagBookNum) {
        cycles.push(item.phaseNum);
      }
    });

    // 存在期数里面的书本不为10本的情况。
    if (cycles.length) {
      notification.error({
        message: "提示",
        description: `第${cycles.join("、")}期书本数量不为${
          info.schoolbagBookNum
        }本`,
      });
      return;
    }

    const res = await func(postData);
    if (res.code == 200) {
      message.success(title + "成功");
      history.goBack();
    }
  };

  return (
    <PageContainer
      loading={loading}
      header={{
        title: (
          <div className="pointer" onClick={() => history.goBack()}>
            <LeftOutlined style={{ marginRight: 10 }} />
            {title}
          </div>
        ),
        breadcrumb: {},
      }}
    >
      <ProCard ghost>
        <ProForm
          layout="horizontal"
          formRef={formRef}
          onFinish={async (values) => {
            console.log("values===", values);
            return handleAddOrUpdate(values);
          }}
          submitter={{
            render: (_, dom) => <FooterToolbar>{dom[1]}</FooterToolbar>,
          }}
          initialValues={{
            schoolbagId,
            cycle,
            phases: Array.from({ length: cycle }, (_, i) => {
              return { phaseNum: i + 1, phaseBooks: [] };
            }),
          }}
        >
          <ProCard>
            <ProFormText
              label="规格名称"
              name="specName"
              rules={[
                { required: true, message: "请输入规格名称" },
                {
                  max: 50,
                  message: "最长为50位",
                },
              ]}
            />
          </ProCard>

          <ProCard
            style={{ marginTop: 20 }}
            title={`每期包含书本（${info.schoolbagBookNum}本/期）`}
          ></ProCard>

          <ProFormList
            name="phases"
            copyIconProps={false}
            deleteIconProps={false}
            creatorButtonProps={false}
            itemRender={({ listDom, action }, { index }) => (
              <ProCard
                bordered
                style={{ marginBlockEnd: 20 }}
                title={`第${index + 1}期`}
                extra={action}
                bodyStyle={{ paddingBlockEnd: 0 }}
              >
                {listDom}
              </ProCard>
            )}
          >
            {(_, index, action2) => {
              return (
                <ProForm.Item
                  name="phaseBooks"
                  rules={[{ required: true, message: "请添加书本" }]}
                >
                  <SetBook
                    key={index}
                    cycle={index + 1}
                    selectedIds={selectedIds}
                    onChange={(val, deleteId) => {
                      console.log("val===", val, deleteId);
                      // selectedIds 里面存放的是所有期里面所选书本的id.
                      setSelectedIds([
                        ...selectedIds.filter((item) => item !== deleteId), // 删除也是调用onChange 只是多了一个deleteId参数
                        ...val.map((item) => item.id),
                      ]);
                    }}
                  />
                </ProForm.Item>
              );
            }}
          </ProFormList>
        </ProForm>
      </ProCard>
    </PageContainer>
  );
};
